import axios from 'axios';
import config from '../config'
import {Notification} from 'element-ui';
let bz=false;
export const HttpGet = async (path = "",data = {}) => {
  let token  = window.localStorage.getItem("token") || "";
  let headers = {
    "Content-Type" : "application/json",
    "token" : token
  }
  return await request({
    method : "GET",
    url : config.requireUrl + path,
    headers : headers,
    params : data
  })
}

export const HttpPost = async (path = "",data = {}) => {
  let token  = window.localStorage.getItem("token") || "";
  let headers = {
    "Content-Type" : "application/json",
    "token" : token
  }
  if(path=='/index.php?s=/admin/passport/login'){
    bz=false;
  }
  return await request({
    method : "POST",
    url : config.requireUrl + path,
    headers : headers,
    data : data
  })
}

const request = async (data = {}) => {
  console.log(data)
  return await axios (data).then((res) => {
    if (res.status >= 400) {
      throw new Error("请求错误");
    } else {
      if (res.data.code == 0) {
        return res.data;
      } else if (res.data.code == -1) {
        if(!bz){
          Notification({
            title: '错误',
            message: "用户身份过期，请重新登录！",
            type: 'error'
          });
        }
        bz=true;
        window.location.href = "/#/login";
        return res.data;
      } else {
        Notification({
           title: '错误',
           message: res.data.msg,
           type: 'error'
        });
        // window.history.back();
        throw new Error(res.data);
      }
    }
  }).catch((error) => {
    throw new Error(error);
  })
}
